import { defineStore } from 'pinia'
import { ref } from 'vue'

export interface UserInfo {
  userId: number
  username: string
  nickname: string
  email: string
  avatar: string
  roles: string[]
  permissions: string[]
}

export const useUserStore = defineStore('user', () => {
  const token = ref<string>('')
  const userInfo = ref<UserInfo | null>(null)
  const roles = ref<string[]>([])
  const permissions = ref<string[]>([])

  // 设置token
  const setToken = (newToken: string) => {
    token.value = newToken
  }

  // 设置用户信息
  const setUserInfo = (info: UserInfo) => {
    userInfo.value = info
    roles.value = info.roles
    permissions.value = info.permissions
  }

  // 登录
  const login = async (loginForm: { username: string; password: string }) => {
    // 这里应该调用实际的登录API
    console.log('登录:', loginForm)
    
    // 模拟登录成功
    const mockToken = 'mock-token-' + Date.now()
    const mockUserInfo: UserInfo = {
      userId: 1,
      username: loginForm.username,
      nickname: '管理员',
      email: 'admin@example.com',
      avatar: '',
      roles: ['admin'],
      permissions: ['*:*:*']
    }
    
    setToken(mockToken)
    setUserInfo(mockUserInfo)
    
    return Promise.resolve()
  }

  // 登出
  const logout = () => {
    token.value = ''
    userInfo.value = null
    roles.value = []
    permissions.value = []
  }

  // 获取用户信息
  const getUserInfo = async () => {
    // 这里应该调用实际的获取用户信息API
    return Promise.resolve(userInfo.value)
  }

  return {
    token,
    userInfo,
    roles,
    permissions,
    setToken,
    setUserInfo,
    login,
    logout,
    getUserInfo
  }
})
